import 'dart:developer';

import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'bean/beans.dart';
import 'package:toast/toast.dart';
import 'main.dart';
import 'page/player.dart';
import 'page/book.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'dart:math' as math;

const main_padding_top = 15.0;
const main_padding_left = 11.0;
const background_color = Color(0xFFefeff4);
const main_radius = 6.0;
const banner_height = 185.0;
const play_controller_bar_height = 60.0;
const main_theme_color = Color(0xffff4d4d);
var status_bar_height = MediaQueryData.fromWindow(window).padding.top;

typedef TapCallback = void Function();

void showToast(String msg, BuildContext context,
    {int duration = 2,
    int gravity = 0,
    Color backgroundColor = main_theme_color,
    Color textColor = Colors.white,
    double backgroundRadius = 20}) {
  Toast.show(msg, context,
      duration: duration,
      gravity: gravity,
      backgroundColor: backgroundColor,
      backgroundRadius: backgroundRadius,
      textColor: textColor);
}

///专辑封面小图
class BookAlbumView extends StatelessWidget {
  final double aspectRatio;
  final Book book;
  final bool centerTitle;
  final bool showPlayCount;

  BookAlbumView(this.book, {this.aspectRatio = 1, this.centerTitle = false, this.showPlayCount = false});

  Widget getTitleWidget() {
    if (centerTitle) {
      return Container(
//        color: Colors.red,
        child: Center(
          child: Text(
            book == null ? "" : book.bookname,
            maxLines: 1,
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: Color(0xff666666)),
          ),
        ),
      );
    } else {
      return Text(
        book == null ? "" : book.bookname,
        maxLines: 1,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: Color(0xff333333)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: GestureDetector(
        onTap: () {
          pushPage(context, BookPage(book));
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            AspectRatio(
              aspectRatio: aspectRatio,
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                child: Container(
                  child: Stack(
                    children: <Widget>[
                      Container(
                        constraints: BoxConstraints.expand(),
                        color: Color(0xFFEFEFF4),
                        child: CachedNetworkImage(
                          placeholder: (BuildContext context, String url) {
                            return Container(
                              color: Color(0xffefeff4),
                              child: Center(
                                child: Image.asset(
                                  "images/bear_d.png",
                                  width: centerTitle ? 46 : 69,
                                  height: centerTitle ? 60 : 89,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            );
                          },
                          imageUrl: book == null ? "" : book.pic,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Align(
                        alignment: FractionalOffset.bottomCenter,
                        child: Offstage(
                          offstage: book == null || book.playCount <= 0 || !showPlayCount,
                          child: Container(
                            height: 22,
                            color: Color(0x40000000),
                            child: Center(
                              child: Text(
                                "${getPlayCountStr(book == null ? 0 : book.playCount)}次播放",
                                style: TextStyle(color: Colors.white, fontSize: 12),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(top: 12),
            ),
            getTitleWidget(),
            Offstage(
              offstage: book == null || centerTitle || book.bookdes == null,
              child: Padding(
                padding: EdgeInsets.only(top: 8),
                child: Text(
                  book == null ? "" : (book.bookdes == null ? "" : book.bookdes),
                  maxLines: 1,
                  style: TextStyle(fontSize: 13, fontWeight: FontWeight.w400, color: Color(0xff666666)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 首页标签view
class TagView extends StatelessWidget {
  final String text;
  final TapCallback onTapMore;

  TagView(this.text, {this.onTapMore}) : assert(text != null);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: 21,
          height: 28,
          child: Image.asset(
            "images/bear.png",
            fit: BoxFit.contain,
          ),
        ),
        Padding(padding: EdgeInsets.only(left: 5)),
        Text(
          text,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xff333333)),
        ),
        Expanded(
          flex: 1,
          child: Text(
            "",
          ),
        ),
        GestureDetector(
          onTap: onTapMore,
          child: Text(
            "更多",
            style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
          ),
        ),
        Icon(
          Icons.arrow_forward_ios,
          size: 14,
          color: Color(0xFFC7C7C7),
        )
      ],
    );
  }
}

///专辑列表样式view
class AlbumListItemView extends StatelessWidget {
  final Book book;

  AlbumListItemView(this.book) : assert(book != null);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GestureDetector(
      onTap: () {
        pushPage(context, BookPage(book));
      },
      child: Container(
        color: Colors.white,
        child: Padding(
          padding: EdgeInsets.only(left: 14, right: 14, top: 14),
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(6)),
                    child: Container(
                      width: 89,
                      height: 89,
                      child: CachedNetworkImage(
                        placeholder: (BuildContext context, String url) {
                          return Container(
                            color: Color(0xffefeff4),
                            child: Center(
                              child: Image.asset(
                                "images/bear_d.png",
                                fit: BoxFit.contain,
                                width: 46,
                                height: 60,
                              ),
                            ),
                          );
                        },
                        imageUrl: book.pic,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(left: 8)),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(padding: EdgeInsets.only(top: 4)),
                      Text(
                        book.bookname == null ? "" : book.bookname,
                        maxLines: 1,
                        overflow: TextOverflow.fade,
                        style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500, color: Color(0xFF333333)),
                      ),
                      Padding(padding: EdgeInsets.only(top: 9)),
                      Text(
                        book.bookdes == null ? "" : book.bookdes,
                        maxLines: 1,
                        overflow: TextOverflow.fade,
                        style: TextStyle(fontSize: 13, fontWeight: FontWeight.normal, color: Color(0xFF666666)),
                      ),
                      Padding(padding: EdgeInsets.only(top: 20)),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            Icons.play_circle_outline,
                            color: Color(0xFFcdcdcd),
                            size: 12,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 2),
                          ),
                          Text(
                            "${getPlayCountStr(book.playCount)}",
                            style: TextStyle(color: Color(0xFF999999), fontSize: 11, fontWeight: FontWeight.w400),
                          ),
                          Padding(padding: EdgeInsets.only(left: 10)),
                          Image.asset(
                            "images/album_ji.png",
                            width: 12,
                            height: 12,
                            color: Color(0xffcdcdcd),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 2),
                          ),
                          Text(
                            "${book.chapterCount}集",
                            style: TextStyle(color: Color(0xFF999999), fontSize: 11, fontWeight: FontWeight.w400),
                          ),
                        ],
                      )
                    ],
                  )
                ],
              ),
              Padding(padding: EdgeInsets.only(top: 14)),
              Divider(
                height: 1,
                color: Color(0xFFdddddd),
              )
            ],
          ),
        ),
      ),
    );
  }
}

///列表项
class TitleItem extends StatelessWidget {
  final Function onTap;

  final String title;
  final String content;
  final Widget img;

  TitleItem(this.title, {this.content, this.onTap, this.img});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Material(
      child: Ink(
        //INK可以实现装饰容器，实现矩形  设置背景色
        color: Colors.white,
        child: InkWell(
          //添加水波纹效果
          onTap: onTap,
          child: Container(
            constraints: BoxConstraints.expand(height: 54),
            child: Row(
              children: <Widget>[
                Padding(
                    padding: EdgeInsets.only(left: 17),
                    child: Text(title, style: TextStyle(fontSize: 16, color: Color(0xff333333)))),
                Expanded(
                    child: Align(
                  alignment: FractionalOffset(1, 0.5),
                  child: Text(
                    content == null ? "" : content,
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w300, color: Color(0xff999999)),
                  ),
                )),
                Offstage(
                  offstage: img == null,
                  child: img == null ? Container() : img,
                ),
                Padding(
                    padding: EdgeInsets.only(right: 15),
                    child: Opacity(
                      opacity: onTap == null ? 0 : 0.4,
                      child: Icon(
                        Icons.arrow_forward_ios,
                        color: Color(0xffc3c3c3),
                        size: 16,
                      ),
                    ))
              ],
            ),
          ),
        ),
      ),
    );
  }
}

///专辑中故事列表样式view
class ChapterListItemView extends StatelessWidget {
  final Chapter _chapter;
  final bool _isPlaying;
  final bool locked;

  ChapterListItemView(this._chapter, this._isPlaying, {this.locked = false}) : assert(_chapter != null);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.only(left: 16, right: 16, top: 16),
        child: Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(6)),
                  child: Container(
                    width: 80,
                    height: 80,
                    child: Stack(
                      alignment: AlignmentDirectional.center,
                      children: <Widget>[
                        CachedNetworkImage(
                          placeholder: (BuildContext context, String url) {
                            return Container(
                              color: Color(0xffefeff4),
                              child: Center(
                                child: Image.asset(
                                  "images/bear_d.png",
                                  fit: BoxFit.contain,
                                  width: 46,
                                  height: 60,
                                ),
                              ),
                            );
                          },
                          imageUrl: _chapter.pic,
                          fit: BoxFit.fill,
                        ),
                        Offstage(
                          offstage: !_isPlaying,
                          child: Stack(
                            children: <Widget>[
                              Container(
                                color: Color(0x60000000),
                              ),
                              Center(
                                child: Image.asset(
                                  "images/play_state1.gif",
                                  width: 20,
                                  height: 23,
                                  fit: BoxFit.fill,
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Padding(padding: EdgeInsets.only(left: 13)),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(padding: EdgeInsets.only(top: 0)),
                      Text(
                        _chapter.name,
                        maxLines: 1,
                        style: TextStyle(
                            fontSize: 17,
                            fontWeight: FontWeight.w500,
                            color: _isPlaying ? main_theme_color : Color(0xFF333333)),
                      ),
                      Padding(padding: EdgeInsets.only(top: 7)),
                      Text(
                        _chapter.des == null ? "" : _chapter.des,
                        maxLines: 1,
                        style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal, color: Color(0xFF666666)),
                      ),
                      Padding(padding: EdgeInsets.only(top: 15)),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            Icons.play_circle_outline,
                            color: Color(0xFFcdcdcd),
                            size: 13,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 2),
                          ),
                          Text(
                            getPlayCountStr(_chapter.playcount),
                            style: TextStyle(color: Color(0xFF999999), fontSize: 11, fontWeight: FontWeight.w400),
                          ),
                          Padding(padding: EdgeInsets.only(left: 10)),
                          Icon(
                            Icons.access_time,
                            color: Color(0xFFcdcdcd),
                            size: 13,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 2),
                          ),
                          Text(
                            _chapter == null ? "" : _chapter.getTimeStr(1),
                            style: TextStyle(color: Color(0xFF999999), fontSize: 11, fontWeight: FontWeight.w400),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
                Opacity(
                  opacity: locked ? 1.0 : 0.0,
//                  offstage: !locked,
                  child: Icon(
                    Icons.lock_outline,
                    size: 27,
                    color: Color(0xffcdcdcd),
                  ),
                )
              ],
            ),
            Padding(padding: EdgeInsets.only(top: 16)),
            Divider(
              height: 1,
              color: Color(0xFFdddddd),
            )
          ],
        ),
      ),
    );
  }
}

///音乐进度条
class MusicSlider extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return null;
  }
}

class _MusicSliderState extends State<MusicSlider> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      constraints: BoxConstraints.expand(height: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[],
      ),
    );
  }
}

class PlayerControllerBarView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _PlayerControllerBarViewState();
  }
}

class _PlayerControllerBarViewState extends State<PlayerControllerBarView>
    with PlayChaptersUpdateListener, EventChannelListener, AutomaticKeepAliveClientMixin {
  double _sliderValue = 0.0;
  double _sliderMax = 1000;

  @override
  void initState() {
    super.initState();
    print("playerController--initState");
    addPlayChaptersUpdateListener(this);
    addEventChannelListener(this);
  }

  @override
  void dispose() {
    super.dispose();
    print("playerController--dispose");
    removePlayChaptersUpdateListener(this);
    removeEventChannelListener(this);
  }

  Widget getPicWidget() {
    Chapter chapter = getNowPlayChapter();
    if (chapter == null) {
      return Container(
        constraints: BoxConstraints.expand(),
        child: Center(
          child: Image.asset(
            "images/bear.png",
            fit: BoxFit.contain,
            width: 35,
            height: 46,
          ),
        ),
      );
    } else {
      return Container(
        constraints: BoxConstraints.expand(),
        child: Image.network(
          chapter == null ? "" : chapter.pic,
          fit: BoxFit.cover,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    super.build(context);
    Chapter chapter = getNowPlayChapter();
//    if (chapter == null) {
//      print("playerController+++++ now chapter==null");
//    } else {
//      print("playerController+++++ now chapter:${chapter.toJson()}");
//    }
    return GestureDetector(
      onTap: () {
        if (chapter != null) {
          pushPage2(context, PlayerPage());
        }
      },
      child: Container(
        height: play_controller_bar_height,
        color: Color.fromRGBO(250, 250, 250, 1),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Divider(
              height: 1,
            ),
            Expanded(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(padding: EdgeInsets.only(left: 5, top: 5)),
                ClipOval(
                  child: Container(
                    constraints: BoxConstraints.expand(width: 53, height: 53),
                    child: Stack(
                      alignment: AlignmentDirectional.center,
                      children: <Widget>[
                        getPicWidget(),
                        Container(
                          color: Color(0x60000000),
                        ),
                        Image.asset(
                          isPlaying() ? "images/play_state1.gif" : "images/play_yp.png",
                          width: 20,
                          height: 23,
                          fit: BoxFit.fill,
                        )
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 0, 0, 4),
                        child: Text(
                          chapter == null ? "" : chapter.name,
                          maxLines: 1,
                          style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                              child: Container(
                                padding: const EdgeInsets.only(left: 4,right: 2),
                            color: Colors.transparent,
                            child: SliderTheme(
                              data: SliderThemeData(
                                trackHeight: 5,
                                inactiveTrackColor: Color(0xFFF9E5E5),
                                activeTrackColor: Color(0xFFFF4D4D),
                                thumbColor: Color(0xFFFF4D4D),
                                trackShape: MySliderTrackShape(),
                                //气泡显示的形式
                                showValueIndicator: ShowValueIndicator.never,
                                thumbShape: RoundSliderThumbShape(enabledThumbRadius: 8),
                                //按下thumb没有overlay效果
                                overlayShape: SliderComponentShape.noOverlay,
                              ),
                              child: Slider(
                                value: _sliderValue,
                                min: 0,
                                max: _sliderMax,
                                onChangeEnd: (value) {
                                  channelSeekToByPercent(value / _sliderMax, chapter.chaptertime);
                                },
                                onChanged: (double value) {
                                  setState(() {
                                    _sliderValue = value;
                                  });
                                },
                                onChangeStart: (value) {},
                              ),
                            ),
                          )),
                          Text(
                            chapter == null ? "" : chapter.getTimeStr(1),
                            style: TextStyle(fontSize: 11, color: Color(0xff333333), fontWeight: FontWeight.w300),
                          ),
                          Padding(padding: EdgeInsets.only(right: 2))
                        ],
                      )
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(right: 6),
                  child: GestureDetector(
                    onTap: () {
                      channelPlayerNext();
                    },
                    child: ClipOval(
                      child: Image.asset(
                        "images/play_next2.png",
                        width: 43,
                        height: 43,
                      ),
                    ),
                  ),
                ),
              ],
            )),
          ],
        ),
      ),
    );
  }

  @override
  void onPlayChaptersUpdate() {
    setState(() {});
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void onEvent(Map map) {
    // TODO: implement onEvent
    String type = map["type"];
    if (type == "player") {
      setState(() {
        String status = map["status"];
        if (status == "onPlayProgress" || status == "onPlayProgress_ios") {
          _sliderValue = getPlayerProgress() * _sliderMax;
        }
      });
    }
  }
}

double getAlbumChildAspectRatio(double devicePixelRatio, int crossAxisCount) {
  if (crossAxisCount == 3) {
    if (devicePixelRatio >= 4) {
      return 3 / 3.75;
    } else if (devicePixelRatio >= 3) {
      return 3 / 4.15;
    } else if (devicePixelRatio >= 2) {
      return 3 / 4.55;
    } else {
      return 3 / 4.95;
    }
  } else if (crossAxisCount == 2) {
    if (devicePixelRatio >= 4) {
      return 3 / 3.98;
    } else if (devicePixelRatio >= 3) {
      return 3 / 4.28;
    } else if (devicePixelRatio >= 2) {
      return 3 / 4.58;
    } else {
      return 3 / 4.88;
    }
  }
  return 0.75;
}

Future pushPage(BuildContext context, Widget widget) {
  return Navigator.of(context).push(PageRouteBuilder(
      pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    return widget;
  }, transitionsBuilder:
          (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return SlideTransition(
      position: new Tween<Offset>(
        begin: const Offset(1.0, 0.0),
        end: const Offset(0.0, 0.0),
      ).animate(animation),
      child: child,
    );
  }));
}

Future pushPage2(BuildContext context, Widget widget) {
  return Navigator.of(context).push(PageRouteBuilder(
      pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    return widget;
  }, transitionsBuilder:
          (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return SlideTransition(
      position: new Tween<Offset>(
        begin: const Offset(0.0, 1.0),
        end: const Offset(0.0, 0.0),
      ).animate(animation),
      child: child,
    );
  }));
}

class MySliderTrackShape extends RoundedRectSliderTrackShape {

  @override
  Rect getPreferredRect({RenderBox parentBox, Offset offset = Offset.zero, SliderThemeData sliderTheme, bool isEnabled = false, bool isDiscrete = false}) {
    // TODO: implement getPreferredRect
    assert(isEnabled != null);
    assert(isDiscrete != null);
    assert(parentBox != null);
    assert(sliderTheme != null);
    final double thumbWidth = sliderTheme.thumbShape.getPreferredSize(isEnabled, isDiscrete).width;
    final double overlayWidth = sliderTheme.overlayShape.getPreferredSize(isEnabled, isDiscrete).width;
    final double trackHeight = sliderTheme.trackHeight;
    assert(overlayWidth >= 0);
    assert(trackHeight >= 0);
    assert(parentBox.size.width >= overlayWidth);
    assert(parentBox.size.height >= trackHeight);

    final double trackLeft = offset.dx + math.max(thumbWidth, overlayWidth)/2;
    final double trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
    final double trackWidth = parentBox.size.width - math.max(thumbWidth, overlayWidth);
    return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
  }

  @override
  void paint(PaintingContext context, Offset offset,
      {RenderBox parentBox,
      SliderThemeData sliderTheme,
      Animation<double> enableAnimation,
      TextDirection textDirection,
      Offset thumbCenter,
      bool isDiscrete = false,
      bool isEnabled = false,
      double additionalActiveTrackHeight = 2}) {
    assert(context != null);
    assert(offset != null);
    assert(parentBox != null);
    assert(sliderTheme != null);
    assert(sliderTheme.disabledActiveTrackColor != null);
    assert(sliderTheme.disabledInactiveTrackColor != null);
    assert(sliderTheme.activeTrackColor != null);
    assert(sliderTheme.inactiveTrackColor != null);
    assert(sliderTheme.thumbShape != null);
    assert(enableAnimation != null);
    assert(textDirection != null);
    assert(thumbCenter != null);
    // If the slider [SliderThemeData.trackHeight] is less than or equal to 0,
    // then it makes no difference whether the track is painted or not,
    // therefore the painting  can be a no-op.
    if (sliderTheme.trackHeight <= 0) {
      return;
    }

    // Assign the track segment paints, which are leading: active and
    // trailing: inactive.
    final ColorTween activeTrackColorTween =
        ColorTween(begin: sliderTheme.disabledActiveTrackColor, end: sliderTheme.activeTrackColor);
    final ColorTween inactiveTrackColorTween =
        ColorTween(begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor);
    final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation);
    final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation);
    Paint leftTrackPaint;
    Paint rightTrackPaint;
    switch (textDirection) {
      case TextDirection.ltr:
        leftTrackPaint = activePaint;
        rightTrackPaint = inactivePaint;
        break;
      case TextDirection.rtl:
        leftTrackPaint = inactivePaint;
        rightTrackPaint = activePaint;
        break;
    }

    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );

    final Radius trackRadius = Radius.circular(trackRect.height / 2);
    final Radius activeTrackRadius = Radius.circular(trackRect.height / 2);

    context.canvas.drawRRect(
      RRect.fromLTRBAndCorners(
        trackRect.left,
        trackRect.top,
        thumbCenter.dx,
        trackRect.bottom,
        topLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius : trackRadius,
        bottomLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius : trackRadius,
      ),
      leftTrackPaint,
    );
    context.canvas.drawRRect(
      RRect.fromLTRBAndCorners(
        thumbCenter.dx,
        trackRect.top,
        trackRect.right,
        trackRect.bottom,
        topRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius,
        bottomRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius,
      ),
      rightTrackPaint,
    );
  }
}

